﻿<%!
	// 查询该医院所拥有的角色列表--roles
	public Message roles(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital");
		Integer hospitalId= input.getInt("hospital_id", -1);
		Where where = new Where("hospital=", hospital);
		if (hospitalId != -1)
				where = new Where("hospital=", hospitalId);
		List<Role> roles = QBuilder.db("basedb").select().from("Role").where(where).query().getResultObj();
		msg.put("data", roles);
		return msg;
	}

	// 所有医院
	public Message hospitals(Input input) {
		Message msg = new Message();
		Integer type = input.getInt("type", -1); //查看一级医院1，二级科室2，全部不传
		Where where = new Where("status=", STATUS_ENABLE);
		if (type != -1)
				where.and("type=", type);
		List<Map> list = QBuilder.db("basedb").select("new map(name as name, hospital as hospital_id, descr as descr)").from("Hospital").where(where).order("hospital", "asc").query().getResultObj();
		msg.put("data", list);
		return msg;
	}
	
	// 所有医院分页
	public Message hospitalByPage(Input input) {
		Message msg = new Message();
		Integer pageNum = input.getInt("page", 1);; 		// 页码
		Integer itemCount = input.getInt("item_count", 16);  // 每一页条目
		Where where = new Where("status=", STATUS_ENABLE);
		List<Map> ranks = QBuilder.db("basedb").select("new map(name as name, hospital as hospital_id, descr as descr)").from("Hospital").where(where).page(itemCount, pageNum).order("hospital", "asc").query().getResultObj();
		List<Long> rankCount = QBuilder.db("basedb").select("count(*)").from("Hospital").where(where).query().getResultObj();
		Long size = rankCount.get(0);
		Map resultMap = new HashMap();
		resultMap.put("rank", ranks);
		resultMap.put("current_page", pageNum);
		resultMap.put("page_count",  size%itemCount == 0?(size/itemCount):(size/itemCount + 1));
		resultMap.put("count", size);
		msg.put("data", resultMap);
		return msg;
	}
	
	// 所有医院
	public Message showHospitalDetail(Input input) {
		Message msg = new Message();
		Integer hospitalId = input.getInt("hospital_id", -1);
		Where where = new Where("status=", STATUS_ENABLE).and("hospital=", hospitalId);
		List<Map> list = QBuilder.db("basedb").select().from("Hospital").where(where).order("hospital", "asc").query().getResultObj();
		if (!isEmpty(list)) {
			msg.put("data", list.get(0));
		}
		return msg;
	}

	// 生成医院编号
	public Message generateHospital(Input input) {
		Message msg = new Message();
		List<Integer> list = QBuilder.db("basedb").select("max(hospital)+1").from("Hospital").where(new Where()).query().getResultObj();
		Map map = new HashMap();
		map.put("hospital_id", 1);
		if (!isEmpty(list))
				map.put("hospital_id", list.get(0));
		msg.put("data", map);
		return msg;
	}

	// 添加医院
	public Message addHospital(Input input) {
		Message msg = new Message();
		Integer hospitalId = input.getInt("hospital_id", -1);
		String name = input.getDesc("name").trim();
		String descr = input.getDesc("descr").trim();
		String alias = input.getDesc("alias").trim();
		Integer type = input.getInt("type", 1);
		Integer parent = input.getInt("parent", -1);
		Integer city = input.getInt("city", 512);
		String json =  input.getDesc("json", "{}");
		Map jsonMap = JSONUtil.fromJson(json, Map.class);
		if (jsonMap == null)
			return new Message(30041, "额外账号信息配置格式不合法");
		List<Map> list = QBuilder.db("basedb").select().from("Hospital").where(new Where("status=", STATUS_ENABLE).and(String.format("(hospital=%s or name = '%s')", new Object[]{hospitalId, name}))).query().getResultObj();
		if (!isEmpty(list))
			return new Message(30031, "该医院名称或编号已存在，不要重复添加");
		Hospital hospital = new Hospital();
		hospital.setName(name);
		hospital.setHospital(hospitalId);
		hospital.setDescr(descr);
		hospital.setAlias(alias);
		hospital.setType(type);
		hospital.setCity(city);
		hospital.setJson(jsonMap);
		if (parent != -1)
			hospital.setParent(parent);
		DBTools.db("basedb").addItem(hospital);
		return msg;
	}

	// 修改医院
	public Message updateHospital(Input input) {
		Message msg = new Message();
		Integer hospitalId = input.getInt("hospital_id", -1);
		String name = input.getDesc("name").trim();
		String descr = input.getDesc("descr").trim();
		String alias = input.getDesc("alias").trim();
		Integer type = input.getInt("type", 1);
		Integer parent = input.getInt("parent", -1);
		Integer city = input.getInt("city", 512);
		String json =  input.getDesc("json", "{}");
		Map jsonMap = JSONUtil.fromJson(json, Map.class);
		if (jsonMap == null)
			return new Message(30041, "额外账号信息配置格式不合法");
		List<Hospital> list = QBuilder.db("basedb").select().from("Hospital").where(new Where("status=", STATUS_ENABLE).and("hospital=", hospitalId)).query().getResultObj();
		if (isEmpty(list))
			return new Message(30041, "不存在这家医院");
		Hospital hospital = list.get(0);
		hospital.setName(name);
		hospital.setHospital(hospitalId);
		hospital.setDescr(descr);
		hospital.setAlias(alias);
		hospital.setType(type);
		hospital.setCity(city);
		hospital.setJson(jsonMap);
		if (parent != -1)
			hospital.setParent(parent);
		DBTools.db("basedb").modItem(hospital, hospital.getId());
		return msg;
	}

	// 查询所有菜单
	public Message allMenus(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital");
		if (hospital != 999)
			return new Message(30041, "您无权访问");
		List<Privilege> privilegeList = QBuilder.db("basedb").queryHql("from Privilege");
		msg.put("data", menus(privilegeList));
		return msg;
	}

	// 根据角色id查询拥有的菜单列表--role_menus
	public Message roleMenus(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital");
		Integer id = input.getInt("role_id");
		// 查询用户对应的权限id
		List<Integer> privList = QBuilder.db("basedb").select("pr.privId").from(" PrivilegeRole as pr").where(new Where("pr.roleId=", id)).query().getResultObj();
		String privIds = "-1,";
		for (int i = 0; i < privList.size(); i++) {
			Integer pid = privList.get(i);
			privIds += pid + ",";
		}
		privIds = Tools.getDesc(privIds, 0, privIds.length()-1);
		List<Privilege> privilegeList = QBuilder.db("basedb").queryHql("from Privilege where id in (" + privIds + ")");
		msg.put("data", menus(privilegeList));
		return msg;
	}

	// 根据用户id有的菜单列表--user_menus
	public Message userMenus(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital");
		Integer id = input.getInt("user_id");
		List<ManageUser> users = QBuilder.db("basedb").select().from("ManageUser").where(new Where("hospital=", hospital).and("id=", id).and("status=", 1)).query().getResultObj();
		if (isEmpty(users)) {
			msg.setErrcodeAndErrmsg(30041, "没有这个用户");
			return msg;
		}
		ManageUser user = users.get(0);
		msg.put("data", getMenusByUser(user));
		return msg;
	}

	// 检测角色名是否可用--check_role
	public Message checkRole(Input input) {
		Message msg = new Message("角色名可用");
		String name = input.getDesc("name").trim();
		Integer hospital = input.getInt("hospital");
		List<Role> roles = QBuilder.db("basedb").select().from("Role").where(new Where("hospital=", hospital).and("name=", name)).query().getResultObj();
		if (!isEmpty(roles)) {
			msg.setErrcodeAndErrmsg(30031, "该角色已经存在");
			return msg;
		}
		return msg;
	}

	// 检测用户名是否可用--check_user
	public Message checkUser(Input input) {
		Message msg = new Message("用户名可用");
		String userName = input.getDesc("user_name").trim();
		List<ManageUser> users = QBuilder.db("basedb").select().from("ManageUser").where(new Where("userName=", userName).and("status=", 1)).query().getResultObj();
		if (!isEmpty(users)) {
			msg.setErrcodeAndErrmsg(30031, "该用户名已经存在");
			return msg;
		}
		return msg;
	}

	// 为该医院添加新角色--add_role
	public Message addRole(Input input) {
		Message msg = new Message("角色添加成功");
		String name = input.getDesc("name").trim();
		String desc = input.getDesc("desc").trim();
		if (name.length() >20) {
			return new Message(30041, "角色名称不能超过20个字");
		}
		if (desc.length() >50) {
			return new Message(30041, "角色描述不能超过50个字");
		}
		List<String> privIdList = stringToList(input.getDesc("priv_ids"));
		Integer hospital = input.getInt("hospital");
		Integer hospitalId= input.getInt("hospital_id", -1);
		if (hospitalId != -1)
				hospital = hospitalId;
		List<Role> roles = QBuilder.db("basedb").select().from("Role").where(new Where("hospital=", hospital).and("name=", name)).query().getResultObj();
		if (!isEmpty(roles)) {
			msg.setErrcodeAndErrmsg(30031, "该角色已经存在");
			return msg;
		}
		Role role = new Role();
		role.setName(name);
		role.setDesc(desc);
		role.setHospital(hospital);
		Integer roleId = (Integer)DBTools.db("basedb").addItem(role);
		for (String privId:privIdList) {
			PrivilegeRole privilegeRole = new PrivilegeRole();
			privilegeRole.setPrivId(Tools.getInt(privId));
			privilegeRole.setRoleId(roleId);
			DBTools.db("basedb").addItem(privilegeRole);
		}
		return msg;
	}

	// 查询该角色下的用户列表--users
	public Message users(Input input) {
		Message msg = new Message();
		Integer id = input.getInt("role_id");
		Integer hospital = input.getInt("hospital");
		Integer hospitalId= input.getInt("hospital_id", -1);
		if (hospitalId != -1)
				hospital = hospitalId;
		List<Map> users = QBuilder.db("basedb").select("new map(u.id as id, u.name as name, u.userName as user_name, u.operatorName as operator_name,concat(FROM_UNIXTIME(u.cTime/1000, '%Y-%m-%d %H:%i:%s'), '') as create_time)").from("UserRole as ur, ManageUser as u").where(new Where("u.hospital=", hospital).and("ur.roleId=", id).and("u.id=ur.userId").and("u.status=", 1)).query().getResultObj();
		msg.put("data", users);
		return msg;
	}

	// 修改角色，可修改内容包含角色名称、拥有权限--update_role
	public Message updateRole(Input input) {
		Message msg = new Message("角色修改成功");
		Integer id = input.getInt("role_id");
		Integer hospital = input.getInt("hospital");
		Integer hospitalId= input.getInt("hospital_id", -1);
		if (hospitalId != -1)
				hospital = hospitalId;
		String name = input.getDesc("name").trim();
		String desc =  input.getDesc("desc").trim();
		if (name.length() >20) {
			return new Message(30041, "角色名称不能超过20个字");
		}
		if (desc.length() >50) {
			return new Message(30041, "角色描述不能超过50个字");
		}
		List<String> privIdList = stringToList(input.getDesc("priv_ids"));
		List<Role> roles = QBuilder.db("basedb").select().from("Role").where(new Where("hospital=", hospital).and("name=", name).and("id!=", id)).query().getResultObj();
		if (!isEmpty(roles)) {
			msg.setErrcodeAndErrmsg(30031, "该角色名称已经存在!");
			return msg;
		}
		roles = QBuilder.db("basedb").select().from("Role").where(new Where("hospital=", hospital).and("id=", id)).query().getResultObj();
		if (isEmpty(roles)) {
			msg.setErrcodeAndErrmsg(30041, "没有找到这个角色!");
			return msg;
		}
		Role role = roles.get(0);
		role.setName(name);
		role.setDesc(desc);
		DBTools.db("basedb").modItem(role, role.getId());
		QBuilder.db("basedb").execHQL("delete from PrivilegeRole where roleId=" + id);
		for (String privId:privIdList) {
			PrivilegeRole privilegeRole = new PrivilegeRole();
			privilegeRole.setPrivId(Tools.getInt(privId));
			privilegeRole.setRoleId(id);
			DBTools.db("basedb").addItem(privilegeRole);
		}
		return msg;
	}

	// 慎重！删除角色，删除角色将随之删除角色下所有用户以及角色所拥有权限--delete_role
	public Message deleteRole(Input input) {
		Message msg = new Message();
		Integer id = input.getInt("role_id");
		Integer hospital = input.getInt("hospital");
		Integer hospitalId= input.getInt("hospital_id", -1);
		if (hospitalId != -1)
				hospital = hospitalId;
		List<Role> list = QBuilder.db("basedb").select().from("Role").where(new Where("hospital=", hospital).and("id=", id)).query().getResultObj();
		if (isEmpty(list)) {
			msg.setErrcodeAndErrmsg(30041, "没有找到该角色!");
			return msg;
		}
		QBuilder.db("basedb").execHQL("delete from ManageUser where id in(select userId from UserRole where roleId=" + id + ")");
		QBuilder.db("basedb").execHQL("delete from UserRole where roleId=" + id);
		QBuilder.db("basedb").execHQL("delete from PrivilegeRole where roleId=" + id);
		QBuilder.db("basedb").execHQL("delete from Role where id=" + id);
		return msg;
	}

	// 添加用户--add_user
	public Message addUser(Input input) {
		Message msg = new Message("用户添加成功");
		Integer roleId = input.getInt("role_id");
		Integer hospital = input.getInt("hospital");
		Integer hospitalId= input.getInt("hospital_id", -1);
		if (hospitalId != -1)
				hospital = hospitalId;
		String name = input.getDesc("name");
		String userName = input.getDesc("user_name");
		String password = input.getDesc("password");
		String repassword = input.getDesc("repassword");
		String skin = input.getDesc("skin");
		ManageUser currentLoginUser = (ManageUser)input.getRequest().getSession().getAttribute("user");
		if(!repassword.equals(password)) {
			msg.setErrcodeAndErrmsg(30041, "两次输入的密码不一致");
			return msg;
		}
		List<ManageUser> list = QBuilder.db("basedb").select().from("ManageUser").where(new Where("user_name=", userName).and("status=", 1)).query().getResultObj();
		if (!isEmpty(list)) {
			msg.setErrcodeAndErrmsg(30031, "用户名重复，请更换其他用户名重试");
			return msg;
		}
		ManageUser user = new ManageUser();
		user.setUserName(userName);
		user.setName(name);
		user.setPassword(Tools.getMD5(password));
		user.setHospital(hospital);
		user.setSkin(skin);
		List<Hospital> hospitals = QBuilder.db("basedb").queryHql("from Hospital where hospital=" + hospital);
		if (isEmpty(hospitals)) {
			return new Message(30041, "没有这家医院");
		}
		user.setHospitalName(hospitals.get(0).getName());
		user.setOperatorName(currentLoginUser.getName());
		user.setOperatorUid(currentLoginUser.getId());
		user.setStatus(1);
		user.setcTime(System.currentTimeMillis());
		Integer id = (Integer)DBTools.db("basedb").addItem(user);
		UserRole userRole = new UserRole();
		userRole.setUserId(id);
		userRole.setRoleId(roleId);
		userRole.setType(1);
		DBTools.db("basedb").addItem(userRole);
		return msg;
	}

	// 修改用户姓名
	public Message updateUser(Input input) {
		Message msg = new Message("信息修改成功");
		Integer id = input.getInt("user_id");
		Integer hospital = input.getInt("hospital");
		Integer hospitalId= input.getInt("hospital_id", -1);
		if (hospitalId != -1)
				hospital = hospitalId;
		String name = input.getDesc("name");
		Integer roleId = input.getInt("role_id");
		List<ManageUser> list = QBuilder.db("basedb").select().from("ManageUser").where(new Where("hospital=", hospital).and("id=", id).and("status=", 1)).query().getResultObj();
		if (isEmpty(list)) {
			msg.setErrcodeAndErrmsg(30041, "没有找到该用户!");
			return msg;
		}
		ManageUser user = list.get(0);
		user.setName(name);
		DBTools.db("basedb").modItem(user, user.getId());
		QBuilder.db("basedb").execHQL("update UserRole set roleId=" + roleId + " where userId=" + id);
		return msg;
	}

	// 删除用户
	public Message deleteUser(Input input) {
		Message msg = new Message("删除成功");
		Integer id = input.getInt("user_id");
		Integer hospital = input.getInt("hospital");
		Integer hospitalId= input.getInt("hospital_id", -1);
		if (hospitalId != -1)
				hospital = hospitalId;
		List<ManageUser> list = QBuilder.db("basedb").select().from("ManageUser").where(new Where("hospital=", hospital).and("id=", id).and("status=", 1)).query().getResultObj();
		if (isEmpty(list)) {
			msg.setErrcodeAndErrmsg(30041, "没有找到该用户!");
			return msg;
		}
		ManageUser user = list.get(0);
		user.setStatus(0);
		DBTools.db("basedb").modItem(user, user.getId());
		return msg;
	}

	// 为用户重置密码--reset_password
	public Message resetPassword(Input input) {
		Message msg = new Message("密码重置成功");
		Integer id = input.getInt("user_id");
		Integer hospital = input.getInt("hospital");
		Integer hospitalId= input.getInt("hospital_id", -1);
		if (hospitalId != -1)
				hospital = hospitalId;
		String password = input.getDesc("password");
		String repassword = input.getDesc("repassword");
		if(!repassword.equals(password)) {
			msg.setErrcodeAndErrmsg(30041, "两次输入的密码不一致");
			return msg;
		}
		List<ManageUser> list = QBuilder.db("basedb").select().from("ManageUser").where(new Where("hospital=", hospital).and("id=", id).and("status=", 1)).query().getResultObj();
		if (isEmpty(list)) {
			msg.setErrcodeAndErrmsg(30041, "没有找到该用户!");
			return msg;
		}
		ManageUser user = list.get(0);
		user.setPassword(Tools.getMD5(password));
		DBTools.db("basedb").modItem(user, user.getId());
		return msg;
	}
%>
